package com.iotimc.attendancesystem.activity;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.datautil.Attend_Info;
import com.iotimc.attendancesystem.datautil.User_Info;
import com.pefis.natives.PfsBioInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
  
  
public class SimpleTable extends LinearLayout implements OnClickListener, OnItemSelectedListener,  
                                                        OnItemClickListener{  
    private Context context;    //上下文  
    private GridView gv_titles; //字段视图  
    private GridView gv_body;   //数据视图  
    private LinearLayout bottomLayout;  //视图底部布局  
    private Button bt_next, bt_pre, bt_first, bt_last;  //按钮：下一页、上一页、manage_home、尾页
    private TextView tv_page, tv_count;   
    private Spinner sp_page;    //页码下拉框  
    private String[][] items;   //[字段][显示的名称]  
    private SimpleAdapter titlesAdatper;    //字段视图适配器  
    private SimpleAdapter datasAdatper; //数据视图适配去  
    private int TableRowCount;          //每页显示条数  
    private int pageID;                 //当前页码  
    private int TotalCount;             //总记录条数  
    private int pageCount;              //总页数  
   // private String TableName;           //表名和查询条件  
    private String[] fields;            //字段名称  
    //private boolean[] isDesc;           //排序方式标记：false-递增排序，true-递减排序  
    private List<Object>  mData;   //数据集合  
    private List<HashMap<String, String> >  dataList = new ArrayList <HashMap<String, String> >() ;   //数据集合  
    
    private int mStartIndex;
    private int mSelectId = -1;
    private int mType ;
    private String mSelectUserNo = "";
    
    private ImageView image;
    

    int mImageWidth = PfsBioInfo.getInstance().face_img_w[0];
	int mImageHeight = PfsBioInfo.getInstance().face_img_h[0];
	private byte[]  mPhotoImage = new byte[mImageWidth*mImageHeight*4];
      
    public SimpleTable(Context context) {  
        super(context);  
        this.context = context;  
    }  
    
      
    public List<Object> getmData() {
		return mData;
	}


	public void setmData(List<Object> mData) {
		this.mData = mData;
	}




	/** 
     * 表格视图 
     * @param context       上下文  
     * @param items         字段名和对应显示名称 
     * @param sql           SQl查询语句 
     * @param displayNum    每页的最大记录数 
     */  
    public SimpleTable(Context context, String[][] items, List<Object> data, int TableRowCount, ImageView image) {  
        super(context);  
        this.context = context;  
        this.items = items;  
        this.TableRowCount = TableRowCount;  
        this.image = image;
        //排序方式标记：false-递增排序，true-递减排序  
        //isDesc = new boolean[items.length];  
        //当前页码  
        pageID = 0;  
        //表名称和查询条件  
        //TableName = sql.toLowerCase().substring(sql.toLowerCase().indexOf(" from ")+5, sql.length()).trim();  
        //记录总数  
        TotalCount = data.size();//SQLiteUtility.getCount(context, "manage_select count(*) from " + TableName);
        //总页码  
        pageCount = TotalCount%TableRowCount==0? TotalCount/TableRowCount-1 : TotalCount/TableRowCount;  
        //字段名称  
        fields = new String[items.length];  
        for (int i = 0; i < items.length; i++) {  
            fields[i] = items[i][0];  
        } 
        
        mData = data;
        dataList.clear();
        
        if (data == null || data.size() <= 0)
        {
        
        }
        else if (mData.get(0) instanceof User_Info)
        {
        	mType = 1;
        	for (Object user :  mData) 
        	{
        		User_Info info = (User_Info)user;
        		
        		HashMap<String, String> temp = new HashMap<String, String>();
        		temp.put("item", String.valueOf(info.getId() ) );
        		dataList.add(temp);
        		
       
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getUserNo() );
        		dataList.add(temp);
        		
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getCompany() );
        		dataList.add(temp);
        		
        		temp = new HashMap<String, String>();
        		
        		String isOnJob = "离职员工";
        		if (info.getIsOnJob() > 0)
        		{
        			isOnJob = "在职员工";
        		}
        		temp.put("item", isOnJob );
        		dataList.add(temp);
        		
        		String permmision = "普通员工";
        		if (info.getUserPermission() > 0)
        		{
        			permmision = "管理员";
        		}
        		
        		temp = new HashMap<String, String>();
        		temp.put("item", permmision);
        		dataList.add(temp);
        		
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getUpdateTime() );
        		dataList.add(temp);
        		
        	}
        }
        else if (mData.get(0) instanceof Attend_Info)
        {
        	mType = 2;
        	for (Object user :  mData) 
        	{
        		Attend_Info info = (Attend_Info)user;
        		HashMap<String, String> temp = new HashMap<String, String>();
        		temp.put("item", String.valueOf(info.getId() ) );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getUserId() );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getCompany() );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getTime() );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getUpdateTime() );
        		dataList.add(temp);
        	}
        }
        else
        {
        	return;
        }
          
        setField(); //字段视图  
        setBody();  //数据视图  
        setBottomLayout();  //底部视图  
        setOrientation(LinearLayout.VERTICAL);   
        addView(gv_titles); //添加视图  
        addView(gv_body);  
        addView(bottomLayout);  
          
    }  
    
    public void setData(List<Object> data)
    {
           
         //排序方式标记：false-递增排序，true-递减排序  
         //isDesc = new boolean[items.length];  
         //当前页码  
         pageID = 0;  
        
         //表名称和查询条件  
         //TableName = sql.toLowerCase().substring(sql.toLowerCase().indexOf(" from ")+5, sql.length()).trim();  
         //记录总数  
         TotalCount = data.size();//SQLiteUtility.getCount(context, "manage_select count(*) from " + TableName);
         //总页码  
         pageCount = TotalCount%TableRowCount==0? TotalCount/TableRowCount-1 : TotalCount/TableRowCount;  
 
         mData = data;
         dataList.clear();
        
         
         if (data == null || data.size() <= 0)
         {
              
         }
         else if (mData.get(0) instanceof User_Info)
         {
        	 mType = 1;
         	for (Object user :  mData) 
         	{
         		User_Info info = (User_Info)user;
         		
         		HashMap<String, String> temp = new HashMap<String, String>();
         		temp.put("item", String.valueOf(info.getId() ) );
         		dataList.add(temp);
         		
         		temp = new HashMap<String, String>();
         		temp.put("item", info.getUserNo() );
         		dataList.add(temp);
         		
         		temp = new HashMap<String, String>();
         		temp.put("item", info.getCompany() );
         		dataList.add(temp);
         		
         		temp = new HashMap<String, String>();
         		String isOnJob = "离职员工";
        		if (info.getIsOnJob() > 0)
        		{
        			isOnJob = "在职员工";
        		}
        		temp.put("item", isOnJob );
        		dataList.add(temp);
         		
         		String permmision = "普通员工";
         		if (info.getUserPermission() > 0)
         		{
         			permmision = "管理员";
         		}
         		
         		temp = new HashMap<String, String>();
         		temp.put("item", permmision);
         		dataList.add(temp);
         		
         		temp = new HashMap<String, String>();
        		temp.put("item", info.getUpdateTime() );
        		dataList.add(temp);
         		
         	}
         }
         else if (mData.get(0) instanceof Attend_Info)
         {
        	 mType = 2;
         	for (Object user :  mData) 
         	{
         		Attend_Info info = (Attend_Info)user;
        		HashMap<String, String> temp = new HashMap<String, String>();
        		temp.put("item", String.valueOf(info.getId() ) );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getUserId() );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getCompany() );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getTime() );
        		dataList.add(temp);
        		temp = new HashMap<String, String>();
        		temp.put("item", info.getUpdateTime() );
        		dataList.add(temp);
         	}
         }
         else
         {
         	return;
         } 
         
       //设置页码下拉框选项  
         List<Integer> list = new ArrayList<Integer>();  
         for(int i = 0; i <= pageCount; i++) {  
             list.add(i);  
         }  
         ArrayAdapter<Integer> pageAdapter = new ArrayAdapter<Integer>(context, R.layout.myspinner, list);  
         sp_page.setAdapter(pageAdapter); 
        
         
        
         
    }
    
    public void toPageRear()
    {
    	 sp_page.setSelection(pageCount);
//    	 pageID = pageCount;
//    	 toPage(pageID); 
    }
    
    public void toPageStart()
    {
    	 pageID = 0;
    	 toPage(pageID); 
    }
    
    public void toPagegu(int pageid)
    {
    	toPage(pageid); 
    	 
    }
    
    public int getPageId()
    {
    	return pageID;
    }
      
      
      
    /** 
     * 设置字段视图 
     */  
    private void setField() {  
        gv_titles = new GridView(context);  
        gv_titles.setNumColumns(items.length);  
          
        //字段标题  
        ArrayList<HashMap<String, String>> titles = new ArrayList<HashMap<String, String>>();  
        for(int i = 0; i < items.length; i++) {  
            HashMap<String, String> map = new HashMap<String, String>();  
            map.put("title", items[i][1]);  
            titles.add(map);  
        }  
        titlesAdatper = new SimpleAdapter(context, titles,   
                R.layout.items, new String[]{"title"}, new int[] {R.id.ItemText});
        gv_titles.setAdapter(titlesAdatper);  
          
        //点击字段标题，改变排序方式  
//        gv_titles.setOnItemClickListener(new OnItemClickListener() 
//        {  
//  
//            @Override  
//            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
//                    long arg3) {  
//  
//                String sql = "manage_select * from (" +   SimpleTable.this.sql +
//                " Limit " + TableRowCount + " Offset " + pageID * TableRowCount + ") tempTable order by " +  
//                items[arg2][0] ;  
//                if(isDesc[arg2]) {  
//                    sql += " asc ";  
//                    isDesc[arg2] = false;  
//                }else {  
//                    sql += " desc ";  
//                    isDesc[arg2] = true;  
//                }  
//                Log.e("sql", sql);    
//                toPage(0, sql);  
//            }  
//        });  
    }  
      
    /** 
     * 设置表格数据视图 
     */  
    private void setBody() {  
        gv_body = new GridView(context); 
        
        gv_body.setNumColumns(items.length);  
              
        toPage(0);    //转到第一页  
        gv_body.setOnItemClickListener(this);   //点击数据事件  
    }  
      
    /** 
     * 设置底部翻页视图， 
     * 由如下组成：manage_home、上一页、下一页、尾页、页码选择、当期页码提示
     */  
    private void setBottomLayout() {  
        //底部容器  
        bottomLayout = new LinearLayout(context);  
        bottomLayout.setOrientation(LinearLayout.HORIZONTAL);  
          
        LayoutParams params = new LayoutParams(  
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        
        
        params.setMargins(133, 0, 0, 0);
        
       // bottomLayout.setLayoutParams(params);
        //翻页按钮  
        bt_pre = new Button(context);   //上一页  
        bt_next = new Button(context);  //下一页  
        bt_first = new Button(context); //manage_home
        bt_last = new Button(context);  //尾页  
        sp_page = new Spinner(context); //页码  
        tv_page = new TextView(context);//页码  
          
        //设置文本  
        bt_pre.setText("上一页");  
        bt_next.setText("下一页");  
        bt_first.setText("manage_home");
        bt_last.setText("尾页");  
        tv_page.setText("页码:");  
        
      
          
        //设置页码下拉框选项  
        List<Integer> list = new ArrayList<Integer>();  
        for(int i = 0; i <= pageCount; i++) {  
            list.add(i);  
        }  
        ArrayAdapter<Integer> pageAdapter = new ArrayAdapter<Integer>(context, R.layout.myspinner, list);  
        sp_page.setAdapter(pageAdapter);  
          
        //设置事件  
        sp_page.setOnItemSelectedListener(this);    //设置下拉框事件  
        bt_first.setOnClickListener(this);  
        bt_pre.setOnClickListener(this);  
        bt_last.setOnClickListener(this);  
        bt_next.setOnClickListener(this);  
          
        //设置文本大小  
        bt_first.setTextSize(24);  
        bt_pre.setTextSize(24);  
        bt_last.setTextSize(24);  
        bt_next.setTextSize(24);  
        tv_page.setTextSize(24);  
        
          
        //添加到底部容器  
        bottomLayout.addView(bt_first, params);  
        bottomLayout.addView(bt_pre, params);  
        bottomLayout.addView(bt_next, params);  
        bottomLayout.addView(bt_last, params);  
        bottomLayout.addView(tv_page, params);  
        bottomLayout.addView(sp_page, params);    
    }  
  
    //设置显示大小  
    public void setSize(View v) {  
        v.setLayoutParams(new android.view.ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
    }  
      
    /** 
     * 翻页点击事件 
     */  
    @Override  
    public void onClick(View v) {  
  
        if(v == bt_first) { //第一页  
            pageID = 0;  
                  
        }else if(v == bt_last) {    //最后一页  
            if(pageCount == 0) {  
                return;  
            }  
            pageID = pageCount;  
                  
        }else if(v == bt_next) {    //下一页  
            if(pageID < pageCount) {  
                ++pageID;  
            } else {  
                return;  
            }  
              
        }else if(v == bt_pre) { //上一页  
            if(pageID <= 0){  
                return;  
            }else {  
                --pageID;  
            }  
        }  
        sp_page.setSelection(pageID); 
        //toPage(pageID);
    }  
      
  
    /** 
     * 页码下拉框选择事件 
     */  
    @Override  
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,  
            long arg3) {  
          
        pageID = arg2;  
        Log.e("onItemSelected:", "selected");  
        toPage(pageID);  
    }  
  
    @Override  
    public void onNothingSelected(AdapterView<?> arg0) {  
        // TODO Auto-generated method stub  
          
    }  
      
    /** 
     * 跳转页面 
     * @param stratIndex 开始页码 
     */  
    public void toPage(int stratIndex) { 
    	
    	int i = 0;
    	int start = stratIndex*TableRowCount*items.length;
    	int end = stratIndex*TableRowCount*items.length + TableRowCount*items.length;
    	mStartIndex = stratIndex;
    	
    	if (end > dataList.size() )
    	{
    	    end = 	dataList.size();
    	}
    	
    	List<HashMap<String, String> > data = new ArrayList<HashMap<String, String> >();
    	
    	for (i=start; i<end; i++)
    	{
    		data.add( (HashMap<String, String> )dataList.get(i) );
    	}
        //设置适配器  
        SimpleAdapter simpleAdapter = new SimpleAdapter(context, data,   
                R.layout.items, new String[]{"item"}, new int[] {R.id.ItemText});  
        gv_body.setAdapter(simpleAdapter);  //重新添加适配器  
    }  
    
    public int getSelectId()
    {
    	return mSelectId;
    }
    
    public String getSelectUserNo()
    {
    	return mSelectUserNo;
    }
    
//    private byte[] getImageData(String dir, int id)
//    {
//	    
//	    String name = id + ".png";
//	    
//		File filename = new File(dir, name);
//
//		if (!filename.exists() )
//		{
//			return null;
//		}
//		
//		
//		 try {
//			FileInputStream in = new FileInputStream(filename);
//			in.read();
//			in.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}	
//    }
  
    /** 
     * 数据项点击事件 
     */  
    @Override  
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {  
          
    	
//        Toast.makeText(context, ((HashMap<String, String>)dataList.get(arg2)).get("item"),   
//                Toast.LENGTH_SHORT).show(); 
    	if (mType != 1)
    	{
    		return;
    	}
    	
    	int start = mStartIndex*TableRowCount*items.length;
    	int end = mStartIndex*TableRowCount*items.length + TableRowCount*items.length;
    	
    	if (end > dataList.size() )
    	{
    	    end = 	dataList.size();
    	}
    	
    	
    	start = start%(TableRowCount*items.length);
    	
    	if (end%(TableRowCount*items.length)  > 0)
    	{
    		end = end%(TableRowCount*items.length);
    	}
    	else
    	{
    		if (end > 0)
    		{
    			end = TableRowCount*items.length;
    		}
    		else
    		{
    			end = 0;
    		}
    	}
    	
    	int i;
    	TextView tv;
    	
    	mSelectId = Integer.valueOf(dataList.get( ( (arg2 + pageID*TableRowCount*items.length)/items.length)*items.length).get("item") );
		mSelectUserNo = dataList.get( ( (arg2 + pageID*TableRowCount*items.length)/items.length)*items.length  + 1).get("item");
		int selectPosition = arg2/items.length + pageID*TableRowCount;
    	
    	//Object o = mData.get(mSelectId);
    	Object o = mData.get(selectPosition);

    	
    	for (i = start; i < end; i++)
    	{
    		tv = (TextView)arg0.getChildAt(i).findViewById(R.id.ItemText);
    		
    		if ( (i/items.length) == (arg2/items.length) )
    		{
    			
    			 tv.setTextColor(Color.rgb(255, 0, 0) );
    		}
    		else
    		{
    			 tv.setTextColor(Color.rgb(255, 255, 255) );
    		}
    	}
    	
    	if (o instanceof User_Info && image != null)
    	{
//    		DataManager dm = MainActivity.getDataManager();
//    		String rect_string = ( (User_Info)o).getUserRect();
//    		int id =  ( (User_Info)o).getId();
//    		Rect rect = dm.getRect(rect_string );
//    		
//    		//此处显示图片
//    		int fileSize = 0;
//			  
//			fileSize = PfsBioInfo.getInstance().ReadByteFromFile(PfsBioInfo.PHOTO_DB_PATH+id+".pv", mPhotoImage, 0);
//			if(fileSize > 0)
//			{
//				Bitmap p = Bitmap.createBitmap(480, 640, Bitmap.Config.ARGB_8888);
//				p.copyPixelsFromBuffer(ByteBuffer.wrap(mPhotoImage) );
//				image.setImageBitmap(Bitmap.createBitmap(p, rect.left, rect.top, rect.right-rect.left+1, rect.bottom-rect.top+1) );
//			}
//			else
//			{
//				image.setImageBitmap(null);
//			}
			
    		
    		User_Info user = (User_Info)o;
    		
    		int fileSize = PfsBioInfo.getInstance().ReadByteFromFile(PfsBioInfo.PHOTO_DB_PATH+user.getId()+".JPEG", mPhotoImage, 0);
			if(fileSize == -1 )
			{
				image.setImageBitmap(null);
				return;
			}
			
			Bitmap  bitmap = BitmapFactory.decodeByteArray(mPhotoImage, 0, fileSize);
			image.setImageBitmap(bitmap);
    	}
    	
    	
    	
//        TextView tv = (TextView)arg1.findViewById(R.id.ItemText);
//        TextView tv1 = (TextView)arg0.getChildAt(0).findViewById(R.id.ItemText);
//        tv.setTextColor(Color.rgb(255, 0, 0) );
//        tv1.setTextColor(Color.rgb(0, 0, 0) );
    }  
  
}  